package com.mfoyou.agent.web.service.file;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MultivaluedMap;


import com.mfoyou.agent.web.service.wx.WXBaseService;
import com.mfoyou.agent.web.utils.wx.WXPICUtil;
import org.apache.poi.util.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.mfoyou.agent.common.dao.domain.HuawuAgentWxInfo;
import org.mfoyou.agent.common.dao.domain.HuawuFile;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.ICommon;
import org.mfoyou.agent.utils.common.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.utils.fastdfs.FastDfsUtil;
import com.mfoyou.agent.web.utils.network.WebUtils;

/**
 * 文件服务类
 *
 * @author hzhang7
 */
@Service
public class FileService {

    @Autowired
    private FastDfsUtil fastDfsUtil;

    @Autowired
    private ICommon iCommon;

    @Autowired
    SessionService sessionService;

    @Value("#{settings['cert_path']}")
    private String cert_path;

    @Value("#{settings['image_server']}")

    private String file_path;

    static Logger logger = Logger.getLogger(FileService.class);

    public List<HuawuFile> uploadFile(HttpServletRequest request, MultipartFormDataInput input) {
        List<HuawuFile> list = new ArrayList<>();
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("file");
        Integer model = null;
        if (request.getParameter("model") != null) {
            model = Integer.parseInt(request.getParameter("model"));
        }
        for (InputPart inputPart : inputParts) {
            try {
                MultivaluedMap<String, String> header = inputPart.getHeaders();
                InputStream inputStream = inputPart.getBody(InputStream.class, null);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                String ext = WebUtils.getFileext(header);
                logger.info("===================圖片上傳 + " + ext);
                //jpg
                String filepath = fastDfsUtil.upload("group1", bytes, "jpg", "");
                HuawuFile fi = new HuawuFile();
                fi.setFileModel(model);
                fi.setFileType("jpg");
                fi.setFilePath(filepath);
                fi.setUserId(sessionService.currentUserId(request));
                int id = iCommon.insertFile(fi);
                fi.setFileId(id);
                list.add(fi);
            } catch (Exception e) {
                logger.error("", e);
                e.printStackTrace();
                list.add(null);
            }
        }
        return list;
    }

    public List<HuawuFile> getFileInfos(List<Integer> ids) {
        return iCommon.getFileInfos(ids);
    }

    public List<HuawuFile> getFiles(Integer currentUserId, Integer model) {
        return iCommon.getFiles(currentUserId, model);
    }

    public List<HuawuFile> uploadFileV2(HttpServletRequest request, MultipartFormDataInput input, Integer userId) {
        List<HuawuFile> list = new ArrayList<>();
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("file");
        for (InputPart inputPart : inputParts) {
            try {
                MultivaluedMap<String, String> header = inputPart.getHeaders();
                InputStream inputStream = inputPart.getBody(InputStream.class, null);
                String ext = WebUtils.getFileext(header).toLowerCase();
                String fileName = "apiclient_cert" + userId + "." + ext;
                String newPath = cert_path;
                logger.info(newPath);
                if (!ext.equals("p12")) {
                    continue;
                }
                String filePath = newPath + "/" + fileName;
                uploadFileToServer(filePath, inputStream);
                HuawuFile fi = new HuawuFile();
                fi.setFileType(ext);
                fi.setFilePath(filePath);
                fi.setUserId(sessionService.currentUserId(request));
                iCommon.insertFile(fi);
                list.add(fi);
            } catch (Exception e) {
                logger.error("", e);
                e.printStackTrace();
                list.add(null);
            }
        }
        return list;
    }

    /**
     * 上传校验文件
     *
     * @param request
     * @param input
     * @param userId
     * @return
     */
    public List<HuawuFile> uploadFileV3(HttpServletRequest request, MultipartFormDataInput input, Integer userId) {
        List<HuawuFile> list = new ArrayList<>();
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("file");
        for (InputPart inputPart : inputParts) {
            try {
                MultivaluedMap<String, String> header = inputPart.getHeaders();
                InputStream inputStream = inputPart.getBody(InputStream.class, null);
                String ext = WebUtils.getFileext(header).toLowerCase();
                String filename = WebUtils.getFilename(header);
                if (!ext.equals("text")) {
                    continue;
                }
                String filePath = file_path + "/" + filename;
                uploadFileToServer(filePath, inputStream);
                HuawuFile fi = new HuawuFile();
                fi.setFileType(ext);
                fi.setFilePath(filePath);
                fi.setUserId(sessionService.currentUserId(request));
                iCommon.insertFile(fi);
                list.add(fi);
            } catch (Exception e) {
                logger.error("", e);
                e.printStackTrace();
                list.add(null);
            }
        }
        return list;
    }

    public void uploadFileToServer(String filePath, InputStream inputStream) {
        try (FileOutputStream out = new FileOutputStream(new File(filePath))) {
            byte[] bytes = IOUtils.toByteArray(inputStream);
            BufferedOutputStream buff = new BufferedOutputStream(out);
            buff.write(bytes);
            buff.flush();
            buff.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private WXBaseService wxBaseService;
    @Autowired
    IAccount iAccount;

    public BufferedImage getWxSharePicture(Integer type, String productUrl, String productPrice, String productName, String page, String scene, String appid, String agentstr) throws Exception {
        HuawuAgentWxInfo huawuAgentWxInfo = iAccount.getAgentWxInfo(Integer.parseInt(agentstr), Integer.parseInt(appid));
        if (huawuAgentWxInfo == null) {
            return null;
        }
        String token = wxBaseService.getToken(huawuAgentWxInfo);
        logger.info("token=" + token);
        BufferedImage pic = WXPICUtil.getPic(token, type, productUrl, productPrice, productName, page, scene);
        return pic;
    }
}
